//
//  TeacherViewController.m
//  inquiry
//
//  Created by 高宇 on 2020/7/1.
//  Copyright © 2020 高宇. All rights reserved.
//

#import "TeacherViewController.h"
#import "GXToast.h"
#import "ULNetHelper.h"
#import "Interface.h"
#import "NSString+MD5.h"
#import "TeacherCell.h"
#import "JRDropMenuView.h"
#import "MJRefresh.h"
#import "TeacherQueDetailVC.h"
#import "leftAlertView.h"

#define SCREEN_WIDTH                 ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT                ([[UIScreen mainScreen] bounds].size.height)

@interface TeacherViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,JRDropMenuDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *arr;
@property (nonatomic , strong) JRDropMenuView * menuView;

@property (strong,nonatomic) UISearchBar *searchBar;

//存放接口数据
@property (nonatomic, strong) NSArray *schoolArr;
@property (nonatomic, strong) NSArray *gradeArr;
@property (nonatomic, strong) NSArray *classArr;
@property (nonatomic, strong) NSArray *queryNameArr;

@property (nonatomic, strong) NSArray *schoolIDArr;
@property (nonatomic, strong) NSArray *gradeIDArr;
@property (nonatomic, strong) NSArray *classIDArr;
@property (nonatomic, strong) NSArray *queryNameIDArr;

@property (nonatomic, strong) NSDictionary *dic;  //存储字典数据
@end

@implementation TeacherViewController

 -(void)viewWillAppear:(BOOL)animated
{
    //隐藏导航栏分割线
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.navigationController.navigationBarHidden = YES;  //隐藏导航栏
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.menuView dismissWithAnimation:NO];
    self.navigationController.navigationBarHidden = NO;  //显示导航栏
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.definesPresentationContext = YES;
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *teacherId = [user objectForKey:@"teacherId"];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"classesId"] = @"";
    dic[@"gradeId"] = @"";
    dic[@"questionnaireId"] = @"";
    dic[@"schoolId"] = @"";
    dic[@"uuid"] = @"";
    dic[@"studentName"] = @"";
    dic[@"questionnaireName"] = @"";
    dic[@"currentPage"] = @(1);
    dic[@"pageSize"] = @(10);
    dic[@"teacherId"] = teacherId;
    self.dic = dic;
    
    //创建UI
    [self createUI];
    [self getData];
    [self getListData];
}

- (void)createUI{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,100)];
    titleView.backgroundColor = [UIColor colorWithRed:125/255.0 green:120/255.0 blue:164/255.0 alpha:1.0];
    
    UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    menuButton.frame = CGRectMake(10, 45, 30, 30);
    [menuButton setImage:[UIImage imageNamed:@"open"] forState:0];
    [menuButton addTarget:self action:@selector(menuClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:menuButton];
    
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(50, 40, SCREEN_WIDTH - 70, 40)];
    self.searchBar.delegate = self;
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.searchBar.placeholder = @"搜索学员姓名";
    self.searchBar.layer.cornerRadius = 19;
    self.searchBar.layer.masksToBounds = YES;
    //设置背景图是为了去掉上下黑线
    self.searchBar.backgroundImage = [[UIImage alloc] init];
    [titleView addSubview:self.searchBar];
    [self.view addSubview:titleView];
    
    //设置搜索框颜色
    UIImage *searchBarBg = [self GetImageWithColor:[UIColor whiteColor] andHeight:32.0f];
    //设置背景图片
    [_searchBar setBackgroundImage:searchBarBg];
    //设置背景色
    [_searchBar setBackgroundColor:[UIColor clearColor]];
    //设置文本框背景
    [_searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    
    //选择框
    self.menuView = [[JRDropMenuView alloc] initWithFrame:CGRectMake(0, 88, [UIScreen mainScreen].bounds.size.width, 44)];
    self.menuView.backgroundColor = [UIColor colorWithRed:125/255.0 green:120/255.0 blue:164/255.0 alpha:1.0];
    self.menuView.delegate = self;
    [self.menuView createJRDropMenuViewWithOption:[self option3]];
    [self.view addSubview:self.menuView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 132, SCREEN_WIDTH, SCREEN_HEIGHT-132) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 73;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //清空tableview多余的空格线
    [self.tableView setTableFooterView:[[UIView alloc]initWithFrame:CGRectZero]];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    // 设置文字
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"释放更新" forState:MJRefreshStatePulling];
    [header setTitle:@"努力加载..." forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.mj_header = header;
    
    MJRefreshBackNormalFooter *mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(jiazai)];
    [mj_footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [mj_footer setTitle:@"松开加载更多" forState:MJRefreshStatePulling];
    _tableView.mj_footer = mj_footer;
    
    [self.view addSubview:self.tableView];
    
    
    NSString *cellID = NSStringFromClass([TeacherCell class]);
    [self.tableView registerNib:[UINib nibWithNibName:cellID bundle:nil] forCellReuseIdentifier:@"cell"];
    
}

//加载更多
- (void)jiazai{
    NSMutableDictionary *dic = [self.dic mutableCopy];
    int pageSize = [dic[@"pageSize"] intValue];
    dic[@"pageSize"] = [NSString stringWithFormat:@"%d",pageSize+10];
    self.dic = dic;
    [self getData];
}

- (UIImage*)GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

- (void)getData{
    [ULNetHelper CancelAllOperations];
    [ULNetHelper POST:dataListPath parameters:self.dic success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        long code = [dic[@"code"] longValue];
        if (code == 200) {
            self.arr = dic[@"data"][@"list"];
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_header endRefreshing];
        }else{
            NSString *msg = responseObject[@"msg"];
            [GXToast showText:msg];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_header endRefreshing];
        }
    }];
}

- (void)getListData{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        dispatch_group_enter(group);   //标志着一个任务追加到 group，执行一次，相当于 group 中未执行完毕任务数+1
        //网络请求无论成功或失败都需要调用dispatch_group_leave(group)方法任务数减一
        [ULNetHelper GET:schoolListPath parameters:nil success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:@"未选择"];
                NSMutableArray *idArray = [NSMutableArray array];
                [idArray addObject:@""];
                NSArray *arr = dic[@"data"];
                for (NSDictionary *dic in arr) {
                    [array addObject:dic[@"schoolName"]];
                    [idArray addObject:dic[@"schoolId"]];
                }
                self.schoolArr = array;
                self.schoolIDArr = idArray;
            }else{
                NSLog(@"学校列表请求失败");
            }
            dispatch_group_leave(group);  //标志着一个任务离开了 group，执行一次，相当于 group 中未执行完毕任务
        }];
    });

    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务2
        dispatch_group_enter(group);
        [ULNetHelper GET:gradesListPath parameters:nil success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:@"未选择"];
                NSMutableArray *idArray = [NSMutableArray array];
                [idArray addObject:@""];
                NSArray *arr = dic[@"data"];
                for (NSDictionary *dic in arr) {
                    [array addObject:dic[@"gradeName"]];
                    [idArray addObject:dic[@"gradeId"]];
                }
                self.gradeArr = array;
                self.gradeIDArr = idArray;
            }else{
                NSLog(@"年级列表请求失败");
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务3
        dispatch_group_enter(group);
        [ULNetHelper GET:classesListPath parameters:nil success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:@"未选择"];
                NSMutableArray *idArray = [NSMutableArray array];
                [idArray addObject:@""];
                NSArray *arr = dic[@"data"];
                for (NSDictionary *dic in arr) {
                    [array addObject:dic[@"classesName"]];
                    [idArray addObject:dic[@"classesId"]];
                }
                self.classArr = array;
                self.classIDArr = idArray;
            }else{
                NSLog(@"班级列表请求失败");
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务4
        dispatch_group_enter(group);
        [ULNetHelper GET:queryNamePath parameters:nil success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:@"未选择"];
                NSMutableArray *idArray = [NSMutableArray array];
                [idArray addObject:@""];
                NSArray *arr = dic[@"data"];
                for (NSDictionary *dic in arr) {
                    [array addObject:dic[@"questionnaireName"]];
                    [idArray addObject:dic[@"questionnaireId"]];
                }
                self.queryNameArr = array;
                self.queryNameIDArr = idArray;
            }else{
                NSLog(@"试卷类型请求失败");
            }
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步任务1、任务2都执行完毕后，回到主线程执行下边任务
        [self.menuView createJRDropMenuViewWithOption:[self option3]];
    });
}


//数据源方法的实现
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TeacherCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[TeacherCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSDictionary *dic = self.arr[indexPath.row];
    NSNumber *studentStatus = dic[@"studentStatus"];
    if ([studentStatus intValue] == 1) {
        cell.selectionImageView.hidden = NO;
    }else{
        cell.selectionImageView.hidden = YES;
    }
    NSString *studentName = dic[@"studentName"];
    NSData *jsonData = [dic[@"userInfo"] dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *userInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSString *gender = userInfo[@"gender"];
    if ([gender isEqualToString:@"woman"]) {
        cell.yuanLabel.backgroundColor = [UIColor colorWithRed:255/256.0 green:119/256.0 blue:139/256.0 alpha:1];
    }else{
        cell.yuanLabel.backgroundColor = [UIColor colorWithRed:119/256.0 green:139/256.0 blue:239/256.0 alpha:1];
    }
    cell.nameLabel.text = studentName;
    cell.numLabel.text = [NSString stringWithFormat:@"学号：%@ ｜ %@",dic[@"studentId"],dic[@"questionnaireName"]];
    if (studentName.length<2) {
        cell.yuanLabel.text = studentName;
    }else{
        cell.yuanLabel.text = [studentName substringFromIndex:studentName.length-2];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSNumber *studentStatus = self.arr[indexPath.row][@"studentStatus"];
    NSString *questionnaireId = self.arr[indexPath.row][@"questionnaireId"];
    NSString *studentId = self.arr[indexPath.row][@"uuid"];
    if ([studentStatus intValue] == 1) {
        //如果答题了   跳转详情页面
        TeacherQueDetailVC *vc = [[TeacherQueDetailVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        vc.questionnaireId = questionnaireId;
        vc.studentId = studentId;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSString *msg = @"该学生还未答题";
        [GXToast showText:msg];
    }
    
    
    
}


- (JROption *)option3
{
    
    JROption * option = JROption.new
    .categoryArrSet(@[
                        JRCategory.new
                        .titleSet(JRTitle.new
                                  .titleNameSet(@"学校")
                                  )
                        .listSet(JRList.new
                                 .listArrSet(self.schoolArr)
                                 )
                        ,

                        JRCategory.new
                        .titleSet(JRTitle.new
                                  .titleNameSet(@"年级")
                                  )
                        .listSet(JRList.new
                                 .listArrSet(self.gradeArr)
                                 .listRowHeightSet(40)
                                 )
                        ,

                        JRCategory.new
                        .titleSet(JRTitle.new
                                  .titleNameSet(@"班级")
                                  )
                        .listSet(JRList.new
                                 .listArrSet(self.classArr)
                                 .listRowHeightSet(40)
                                 )
                        ,

                        JRCategory.new
                        .titleSet(JRTitle.new
                                  .titleNameSet(@"试卷类型")
                                  )
                        .listSet(JRList.new
                                 .listArrSet(self.queryNameArr)
                                 .listRowHeightSet(40)
                                 )
                        ,
                      ]
                    );
    return option;
}

- (void)jrDropMenuView:(JRDropMenuView *)jrDropMenuView ResultArr:(NSMutableArray <JRDropMenuItemModel *>*)resultArr{
    JRDropMenuItemModel *model0 = resultArr[0];
    JRDropMenuItemModel *model1 = resultArr[1];
    JRDropMenuItemModel *model2 = resultArr[2];
    JRDropMenuItemModel *model3 = resultArr[3];
    
    NSString *schoolId = self.schoolIDArr[model0.index];
    NSString *gradeId = self.gradeIDArr[model1.index];
    NSString *classesId = self.classIDArr[model2.index];
    NSString *questionnaireId = self.queryNameIDArr[model3.index];
    
    NSMutableDictionary *dic = [self.dic mutableCopy];
    dic[@"classesId"] = classesId;
    dic[@"gradeId"] = gradeId;
    dic[@"questionnaireId"] = questionnaireId;
    dic[@"schoolId"] = schoolId;
    self.dic = dic;
    [self getData];
}

//搜索框编辑时调用
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)searchText
{
    //处理搜索事件。。。
    NSLog(@"searchText = %@",searchText);
    NSMutableDictionary *dic = [self.dic mutableCopy];
    dic[@"studentName"] = searchText;
    self.dic = dic;
    [self getData];
}

//抽屉点击事件
- (void)menuClick{
    leftAlertView * alertV = [[leftAlertView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view.window addSubview:alertV];
}

@end
